package com.ai.opc;

import cn.hutool.core.util.ObjectUtil;
import com.ai.common.constant.OpcConstant;
import com.ai.entity.made.OpcNodeInfo;
import com.ai.entity.made.OpcServerInfo;
import com.ai.service.made.IOpcNodeInfoService;
import com.ai.service.made.IOpcServerInfoService;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.milo.opcua.sdk.client.api.UaClient;
import org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaSubscription;
import org.eclipse.milo.opcua.stack.core.types.builtin.NodeId;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 监听指定节点
 * @Author jiaok
 * @Date 2024-11-14 16:26
 */
@Slf4j
public class OpcNodeRunnable implements Runnable{

    private IOpcServerInfoService iOpcServerInfoService;

    private OpcNodeInfo opcNodeInfo;


    private IOpcNodeInfoService iOpcNodeInfoService;

    public OpcNodeRunnable(OpcNodeInfo opcNodeInfo,IOpcServerInfoService iOpcServerInfoService,IOpcNodeInfoService iOpcNodeInfoService) {
        this.opcNodeInfo = opcNodeInfo;
        this.iOpcServerInfoService = iOpcServerInfoService;
        this.iOpcNodeInfoService = iOpcNodeInfoService;
    }

    @Override
    public void run() {
        //开始监听节点信息
        UaClient opcUaClient = OpcConstant.OPC_SERVER_ID_CLIENT_MAP.get(this.opcNodeInfo.getOpcServerInfoId());
        if (ObjectUtil.isEmpty(opcUaClient)){
            //opc客户端为空
            new RuntimeException("opc客户端未建立连接，请检查opc server 信息").printStackTrace();
            // TODO: 2024-11-14 修改opc server的状态为 连接失败
            iOpcServerInfoService.update(new UpdateWrapper<OpcServerInfo>()
                    .eq("id",this.opcNodeInfo.getOpcServerInfoId())
                    .set("state","-1"));

        }else {
            NodeId nodeId = new NodeId(this.opcNodeInfo.getNamespace(), this.opcNodeInfo.getIdentifier());
            try {
//                UaSubscription uaSubscription = OpcConstant.OPC_CLIENT_SUBSCRIBE_MAP.get(this.opcNodeInfo.getOpcServerInfoId());
                new DynamicOpcNodeSubscriber(opcUaClient,iOpcNodeInfoService).addMonitoredItem(nodeId);
            } catch (Exception e) {
                log.error("===========================  监听节点信息失败 ：{} ===========================", this.opcNodeInfo.getIdentifier());
                e.printStackTrace();
            }
        }
    }
}
